package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    DtsAdminService dtsAdminService;
    @Autowired
    DtsRoleService dtsRoleService;
    @Autowired
    DtsPermissionService dtsPermissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DtsAdmin admin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
        Integer[] roleIds = admin.getRoleIds();
        Set<String > roles=dtsRoleService.findRoleById(roleIds);
        Set<String>permissions=dtsPermissionService.findPermissionById(roleIds);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char [])authenticationToken.getCredentials());
        DtsAdmin admin=dtsAdminService.findByUsername(username);
        if(admin==null){
            throw new UnknownAccountException("未知账户异常");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (password==null||!passwordEncoder.matches(password,admin.getPassword())) {
            throw new CredentialsException("密码错误");
        }
        if (admin.getDeleted()) {
            throw new LockedAccountException("账户已锁定");
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin,password,admin.getUsername());
        return authenticationInfo;
    }
}
